/*
 * Copyright 2010 Christoph Widulle (christoph.widulle@googlemail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */



package com.android1.amarena2d.commons.collections;


public class FixedSizeStack<E> {

    private static final int INITIAL_SIZE = 30;
    private E[] stack;
    private int index;

    public FixedSizeStack() {
        this(INITIAL_SIZE);
    }

    public FixedSizeStack(E[] stack) {
        this.stack = stack;
        index = stack.length;
    }

    public FixedSizeStack(int initialSize) {
        stack = (E[]) new Object[initialSize];
        index = 0;
    }

    public int size() {
        return index;
    }

    public boolean isEmpty() {
        return index <= 0;
    }

    public void push(E element) {
        if (index == stack.length)
            throw new IndexOutOfBoundsException("FixedStack exceeded.");
        stack[index++] = element;
    }

    public E pop() {
        if (index <= 0) {
            return null;
        }
        E e = stack[--index];
        stack[index] = null;
        return e;
    }


    public void clear() {
        index = 0;
    }

    public boolean contains(E e) {
        for (int i = 0; i < index; i++) {
            if (stack[i].equals(e))
                return true;
        }
        return false;
    }

    public E peek() {
        return stack[index - 1];
    }

    public void cleanup() {
        for (int i = index; i < stack.length; i++) {
            stack[i] = null;
        }
    }
}
